require 'date'
load 'tutem_utils.rb'

#这是某一个时间段的输出
=begin
recs = getRepPerformanceDuring Time.parse('2023-05-08 00:00:00').to_i, Time.parse('2023-05-15 00:00:00').to_i, 'MayWK2'
text = formatRepPerformanceRecsInText recs, defaultMonthlyKpiFormat, 'SALES', '', 'rep_id', 'asc'
puts text
recs = getRepPerformanceDuring Time.parse('2023-03-01 00:00:00').to_i, Time.parse('2023-03-31 24:00:00').to_i, '23Mar'
text = formatRepPerformanceRecsInText recs, defaultMonthlyKpiFormat, 'SALES', '', 'rep_id', 'asc'
puts text
=end

#生成22全年的业绩，这里的总实际销售额可以与后台完美对上
#recs = getRepPerformanceDuring Time.parse('2023-01-01 00:00:00').to_i, Time.parse('2023-06-30 24:00:00').to_i, 'half-year-2023'; dump_hash_to_excel recs, 'half-year-2023', true

#day = '2023-06-30'
#report = genDailySalesPerformanceFor day; puts report
#report = genMonthlySalesKpiTillDay day; puts report
#report = genDailyUserReport; puts report

def generate_current_sales_forecast
  # 获取当前日期的年和月
  current_date = Date.today
  current_year = current_date.year
  current_month = current_date.month

  # 计算上一个月的年和月
  last_month_date = current_date.prev_month
  last_month_year = last_month_date.year
  last_month = last_month_date.month

  puts "正在生成#{last_month}月（#{last_month_year}年）的销售业绩以及#{current_month}月的预测报告..."

  # 调用 createMonthlyForecast 函数
  createMonthlySalesForecastOn current_year, current_month

  puts "已完成，请继续在命令行中运行 【start sales-report】 打开数据目录后将数据复制后黏贴到本地电脑"

end

#createMonthlySalesForecastOn 2023, 9 #用八月份的数据生成九月份的销售模板
generate_current_sales_forecast
exit

def getDateRange code = 'END_OF_MONTH'

    start_date = Date.new(2022, 1, 1)
    end_date = Date.new(2023, 6, 1)

    date_range = []
    date_range = (start_date..end_date).select { |date| date.day == 1 }.map { |date| date.strftime('%Y-%m-%d') } if code == 'START_OF_MONTH'

    if code == 'END_OF_MONTH'
        current_date = start_date
        while current_date <= end_date
            last_day = Date.new(current_date.year, current_date.month, -1)
            date_range << last_day.strftime('%Y-%m-%d')
            current_date = current_date.next_month
        end
    end

    return date_range

end

date_range = getDateRange 'END_OF_MONTH'
date_range.each do |day|
    report = genMonthlySalesKpiTillDay day; puts report
end
